//
//  CPSVideoEditDemoController.m
//  CollTest
//
//  Created by codew on 1/4/22.
//

#import "CPSVideoEditDemoController.h"
#import "CPSVEP_CustomCameraViewController.h"
#import "HXCustomAssetModel.h"
#import "HXPhotoManager.h"
#import "HXPhotoSubViewCell.h"
#import "HXPhotoView.h"

#import "UIViewController+HXExtension.h"

@interface CPSVideoEditDemoController ()
@property (strong, nonatomic) HXPhotoManager *photoManager;

@end

@implementation CPSVideoEditDemoController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.view.backgroundColor = [UIColor redColor];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
}

- (IBAction)btnHXClick:(id)sender {
    [self setupManagerConfig];
    // 去掉dismiss的动画方便选择完成后present
    self.photoManager.selectPhotoFinishDismissAnimated = NO;
    self.photoManager.cameraFinishDismissAnimated = NO;

    
    
    
    
    
    
    if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        [self.view hx_showImageHUDText:[NSBundle hx_localizedStringForKey:@"无法使用相机!"]];
        return;
    }
    
    HXWeakSelf
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (granted) {
                CPSVEP_CustomCameraViewController *vc = [[CPSVEP_CustomCameraViewController alloc] init];
                vc.delegate = (id)weakSelf;
                vc.manager = weakSelf.photoManager;
                vc.isOutside = YES;
                HXCustomNavigationController *nav = [[HXCustomNavigationController alloc] initWithRootViewController:vc];
                nav.isCamera = YES;
                nav.supportRotation = weakSelf.photoManager.configuration.supportRotation;
                nav.modalPresentationStyle = UIModalPresentationOverFullScreen;
                nav.modalPresentationCapturesStatusBarAppearance = YES;
                [weakSelf presentViewController:nav animated:YES completion:nil];
            }else {
                [HXPhotoTools showUnusableCameraAlert:weakSelf];
            }
        });
    }];
    
    
}


///// 拍照/录制完成
///// @param viewController self
///// @param model 资源模型
//- (void)customCameraViewController:(CPSVEP_CustomCameraViewController *)viewController
//                           didDone:(HXPhotoModel *)model
//{
//    NSLog(@"%s", __func__);
//}
//
///// 取消
///// @param viewController self
//- (void)customCameraViewControllerDidCancel:(CPSVEP_CustomCameraViewController *)viewController
//{
//    NSLog(@"%s", __func__);
//}
//
//- (void)customCameraViewControllerFinishDismissCompletion:(CPSVEP_CustomCameraViewController *)viewController
//{
//    NSLog(@"%s", __func__);
//}
//- (void)customCameraViewControllerCancelDismissCompletion:(CPSVEP_CustomCameraViewController *)viewController
//{
//    NSLog(@"%s", __func__);
//}


- (HXPhotoManager *)photoManager {
    if (!_photoManager) {
        _photoManager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhotoAndVideo];
        
        _photoManager.configuration.type = HXConfigurationTypeWXMoment;
        _photoManager.configuration.localFileName = @"hx_WxMomentPhotoModels";
        _photoManager.configuration.showOriginalBytes = YES;
        _photoManager.configuration.showOriginalBytesLoading = YES;
//        _photoManager.configuration.clarityScale = 2.f;

        _photoManager.viewWillAppear = ^(UIViewController *viewController) {
            NSSLog(@"%@：viewWillAppear", viewController.class);
        };
    
    }
    return _photoManager;
}
- (void)setupManagerConfig {
    // 因为公用的同一个manager所以这些需要在跳转前设置一下
    self.photoManager.type = HXPhotoManagerSelectedTypePhotoAndVideo;
    self.photoManager.configuration.singleJumpEdit = NO;
    self.photoManager.configuration.singleSelected = NO;
    self.photoManager.configuration.lookGifPhoto = YES;
    self.photoManager.configuration.lookLivePhoto = YES;
    self.photoManager.configuration.photoEditConfigur.aspectRatio = HXPhotoEditAspectRatioType_None;
    self.photoManager.configuration.photoEditConfigur.onlyCliping = NO;
//    self.photoManager.configuration.photoEditConfigur.aspectRatio = HXPhotoEditAspectRatioType_1x1;
//    self.photoManager.configuration.photoEditConfigur.onlyCliping = YES;
//    self.photoManager.configuration.photoEditConfigur.isRoundCliping = YES;
}
/**
 合并视频
 */
//Obj-c
//- (void)combVideos {
//    NSBundle *mainBundle = [NSBundle mainBundle];
//    NSString *firstVideo = [mainBundle pathForResource:@"1" ofType:@"mp4"];
//    NSString *secondVideo = [mainBundle pathForResource:@"2" ofType:@"mp4"];
//
//    NSDictionary *optDict = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
//    AVAsset *firstAsset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:firstVideo] options:optDict];
//    AVAsset *secondAsset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:secondVideo] options:optDict];
//
//    AVMutableComposition *composition = [AVMutableComposition composition];
//    //为视频类型的的Track
//    AVMutableCompositionTrack *compositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
//    //由于没有计算当前CMTime的起始位置，现在插入0的位置,所以合并出来的视频是后添加在前面，可以计算一下时间，插入到指定位置
//    //CMTimeRangeMake 指定起去始位置
//    CMTimeRange firstTimeRange = CMTimeRangeMake(kCMTimeZero, firstAsset.duration);
//    CMTimeRange secondTimeRange = CMTimeRangeMake(kCMTimeZero, secondAsset.duration);
//    [compositionTrack insertTimeRange:secondTimeRange ofTrack:[secondAsset tracksWithMediaType:AVMediaTypeVideo][0] atTime:kCMTimeZero error:nil];
//    [compositionTrack insertTimeRange:firstTimeRange ofTrack:[firstAsset tracksWithMediaType:AVMediaTypeVideo][0] atTime:kCMTimeZero error:nil];
//
//    //只合并视频，导出后声音会消失，所以需要把声音插入到混淆器中
//    //添加音频,添加本地其他音乐也可以,与视频一致
//    AVMutableCompositionTrack *audioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
//    [audioTrack insertTimeRange:secondTimeRange ofTrack:[firstAsset tracksWithMediaType:AVMediaTypeAudio][0] atTime:kCMTimeZero error:nil];
//    [audioTrack insertTimeRange:firstTimeRange ofTrack:[firstAsset tracksWithMediaType:AVMediaTypeAudio][0] atTime:kCMTimeZero error:nil];
//
//    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//    NSString *filePath = [cachePath stringByAppendingPathComponent:@"comp.mp4"];
//    AVAssetExportSession *exporterSession = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetHighestQuality];
//    exporterSession.outputFileType = AVFileTypeMPEG4;
//    exporterSession.outputURL = [NSURL fileURLWithPath:filePath]; //如果文件已存在，将造成导出失败
//    exporterSession.shouldOptimizeForNetworkUse = YES; //用于互联网传输
//    [exporterSession exportAsynchronouslyWithCompletionHandler:^{
//        switch (exporterSession.status) {
//            case AVAssetExportSessionStatusUnknown:
//                NSLog(@"exporter Unknow");
//                break;
//            case AVAssetExportSessionStatusCancelled:
//                NSLog(@"exporter Canceled");
//                break;
//            case AVAssetExportSessionStatusFailed:
//                NSLog(@"exporter Failed");
//                break;
//            case AVAssetExportSessionStatusWaiting:
//                NSLog(@"exporter Waiting");
//                break;
//            case AVAssetExportSessionStatusExporting:
//                NSLog(@"exporter Exporting");
//                break;
//            case AVAssetExportSessionStatusCompleted:
//                NSLog(@"exporter Completed");
//                break;
//        }
//    }];
//}

@end
